package com.haisen.controller;

import com.alibaba.fastjson.JSON;
import com.haisen.core.annotation.SystemLog;
import com.haisen.core.utils.PageResultSet;
import com.haisen.core.utils.Result;
import com.haisen.core.utils.ResultCodeEnum;
import com.haisen.dataobject.dto.ItemDto;
import com.haisen.dataobject.entity.Item;
import com.haisen.dataobject.entity.ItemParamValue;
import com.haisen.dataobject.entity.Log;
import com.haisen.dataobject.query.ItemQuery;
import com.haisen.exception.BizException;
import com.haisen.service.AreaService;
import com.haisen.service.ItemCatService;
import com.haisen.service.ItemParamValueService;
import com.haisen.service.ItemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/item")
@Slf4j
public class ItemController {

    @Autowired
    private ItemService itemService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private ItemCatService itemCatService;
    @Autowired
    private ItemParamValueService itemParamValueService;

    //todo:地区关系读取

    @GetMapping("/sample")
    public String pagetest(Model model) {
        setCommonData(model);
        return "product/sample";
    }



    @GetMapping
    @RequiresPermissions("item:view")
    public String page(Model model) {
        setCommonData(model);
        return "product/item";
    }

    @ResponseBody
    @RequestMapping("/list")
    @RequiresPermissions("item:view")
    public PageResultSet<ItemDto> list(ItemQuery itemQuery) {
        log.info("查询对象条件：{}",JSON.toJSONString(itemQuery));
        return itemService.findByPage(itemQuery);
    }


    @ResponseBody
    @PostMapping("/create")
    @RequiresPermissions("item:create")
    @SystemLog("产品管理创建产品")
    public Result create(@Valid ItemDto itemDTO) {
        log.info("访问了controller,itemdto={},json={}",JSON.toJSONString(itemDTO),JSON.toJSONString(itemDTO.getParamjson()));


        //构建
        Item item = new Item();
        try {
            BeanUtils.copyProperties(item,itemDTO);
            //多重映射，这里重新拷贝属性
            item.setAreaId(itemDTO.getCountryId());
            item.setAreaName(itemDTO.getCountryName());
        } catch (IllegalAccessException e) {
            throw new BizException(ResultCodeEnum.FAILED_ITEM_COPY_PROPERIIES);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
       // log.info("待插入商品：{}",JSON.toJSONString(item));
        itemService.createItem(item);
        //获取插入后的Id
         Long itemId = itemService.findMaxId();
        //调用itemparamService来批量添加list
          List<ItemParamValue> itemParamValueList = new ArrayList<>();
         itemDTO.getItemParamValueList().forEach( e ->{
             log.info("itemId:{},paramId:{},paramValue:{}",itemId,e.getParamId(),e.getParamValue());
             itemParamValueList.add(new ItemParamValue(itemId,e.getItemName(),e.getParamId(),e.getParamName(),e.getParamValue()));
         });

       itemParamValueService.createBatch(itemParamValueList);

        return Result.success();
    }



    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("item:update")
    @SystemLog("产品管理更新产品")
    public Result update(ItemDto itemDto) {
        //临时这里转换下，dto->item
        Item item = new Item();
        try {
            BeanUtils.copyProperties(item,itemDto);
            //多重映射，这里重新拷贝属性
            item.setAreaId(itemDto.getCountryId());
            item.setAreaName(itemDto.getCountryName());
        } catch (IllegalAccessException e) {
            throw new BizException(ResultCodeEnum.FAILED_ITEM_COPY_PROPERIIES);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        log.info("更新对象={}",JSON.toJSONString(item));
        itemService.updateItem(item);
        item.getItemParamValueList().forEach( o -> {
            itemParamValueService.update(o);
        });

        return Result.success();
    }

    @ResponseBody
    @PostMapping("/delete")
    @RequiresPermissions("item:delete")
    @SystemLog("产品管理删除产品")
    public Result delete(@RequestParam("id") Long[] ids) {
        log.info("要删除的ids:{}", JSON.toJSON(ids));
        Arrays.asList(ids).forEach(id -> itemService.deleteItem(id));
        return Result.success();
    }


    private void setCommonData(Model model) {
        model.addAttribute("areaList",areaService.getAllCity());
        model.addAttribute("itemCatList",itemCatService.findAll());
        model.addAttribute("itemList", itemService.findAll());
    }

}
